package com.youthfilmic.yuejian.exception;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.youthfilmic.yuejian.dao.TextInfoDao;
import com.youthfilmic.yuejian.domain.TextInfo;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import org.springframework.web.servlet.view.RedirectView;

/**
 * @author 由伟希
 * @version v0.1
 * @Date 2015.4.21
 * @instruction 主要是处理没有授权的操作异常
 * 
 * 
 * 实现自己的HandlerExceptionResolver，HandlerExceptionResolver是一个接口，
 * springMVC本身已经对其有了一个自身的实现——DefaultExceptionResolver,
 * 该解析器只是对其中的一些比较典型的异常进行了拦截处理。
 * 
 * */
public class ExceptionHandler implements HandlerExceptionResolver{
	@Resource
	private TextInfoDao textInfoDao;
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request , HttpServletResponse response, Object handler, Exception ex) {
		
		/*if (ex instanceof ConversionFailedException) {
			return new ModelAndView(new RedirectView("/error/500"));
		}else if (ex instanceof IllegalArgumentException) {
            return new ModelAndView(new RedirectView("/error/404"));
        }else*/
		{
        	//记录500错误
        	StackTraceElement[] elements =  ex.getStackTrace();
			Throwable cause = ex.getCause();
    		StringBuffer buffer = new StringBuffer();
    		buffer.append("<p>");
    		for (StackTraceElement ele: elements){
    			buffer.append(ele.toString());
    			buffer.append("<br>");
    		}
			buffer.append("</p>");
			if (cause != null) buffer.append(cause.toString());
    		buffer.append("</p>");


			TextInfo t = new TextInfo();
			t.setText(buffer.toString());
			textInfoDao.save(t);
			return new ModelAndView(new RedirectView("/error/500"));
		}

	}

	 
}
